<template>
  <div class="init-layout">
    <div class="init-title">
      <h2 class="init-title-txt">配置应用信息</h2>
    </div>
    <div class="init-content">
      <Form :model="formItem" :label-width="110" :rules="itemRules" ref="formItem">
        <div class="init-content-app">
          <h2 class="init-content-title">1、应用获取用户信息选择(勾选该应用获取用户的敏感信息，需咨询bd，默认手机号／姓名／身份证)</h2>
          <div class="init-app-checkbox">
            <Form-item prop="userInfos">
              <Checkbox-group v-model="formItem.userInfos">
                <Checkbox :label="item.code" v-for="(item,index) in intCheckbox" :key="index">
                  <span>{{item.name}}</span>
                </Checkbox>
              </Checkbox-group>
            </Form-item>
          </div>
        </div>
        <div class="init-app-id clearfix">
          <h2 class="init-content-title fl">2、应用名称:</h2>
          <Form-item prop="name">
            <Input v-model="formItem.name" placeholder="请输入该卡片名称" title="请输入该卡片名称"></Input>
          </Form-item>
        </div>
        <div class="init-app-id clearfix">
          <h2 class="init-content-title fl">3、输入APPID:</h2>
          <Form-item prop="appId">
            <Input v-model="formItem.appId" placeholder="请用该城市对应支付宝账号登陆支付宝开发平台获取应用的16位appid"
                   title="请用该城市对应支付宝账号登陆支付宝开发平台获取应用的16位appid"></Input>
          </Form-item>
        </div>
        <div class="init-app-id clearfix">
          <h2 class="init-content-title fl">4、支付宝会员卡TemplateId:</h2>
          <Form-item prop="templateId">
            <Input v-model="formItem.templateId" placeholder="请咨询支付宝技术人员获取25位TemplateId"
                   title="请咨询支付宝技术人员获取25位TemplateId"></Input>
          </Form-item>
        </div>
        <div class="init-app-config">
          <h2 class="init-content-title">
            5、开发配置
            <span></span>
          </h2>
          <div class="init-config-total clearfix">
            <div class="init-config-base fl">
              <h2 class="init-config-title">
                基础环境
              </h2>
              <div class="init-base-all">
                <Form-item label="支付宝网关：" prop="gateWay">
                  <Input v-model="formItem.gateWay" placeholder="请输入"></Input>
                </Form-item>
                <Form-item label="授权回调地址：" prop="authReturnUrl">
                  <Input v-model="formItem.authReturnUrl" placeholder="请咨询小码技术同学获取"></Input>
                </Form-item>
                <h2 class="init-config-title">将卡片样式&卡片菜单配置效果图发给支付宝后获取以下参数</h2>
                <Form-item label="城市编码：" prop="cityCode" style="marginTop: 20px">
                  <Input v-model="formItem.cityCode" placeholder="请咨询小码技术同学获取6位数字"></Input>
                </Form-item>
                <Form-item label="卡类型：" prop="cardType">
                  <Input v-model="formItem.cardType" placeholder="请咨询支付宝技术人员获取，首位大写字母＋7位数字"></Input>
                </Form-item>
                <Form-item label="开卡参数bizType：" prop="bizType">
                  <Input v-model="formItem.bizType" placeholder="请输入" disabled></Input>
                </Form-item>
                <Form-item label="开卡链接scence：" prop="sence">
                  <Input v-model="formItem.sence" placeholder="请输入" disabled></Input>
                </Form-item>
                <Form-item label="链接subsence：" prop="subSence">
                  <Input v-model="formItem.subSence" placeholder="请咨询支付宝技术人员获取"></Input>
                </Form-item>
                <Form-item label="领卡验证sourse：" prop="openCardVerifySource">
                  <Input v-model="formItem.openCardVerifySource" placeholder="请咨询支付宝技术人员获取"></Input>
                </Form-item>
                <Form-item label="开卡成功sourse：" prop="openCardSuccessSource">
                  <Input v-model="formItem.openCardSuccessSource" placeholder="请咨询支付宝技术人员获取"></Input>
                </Form-item>
                <Form-item label="用卡乘车sourse：" prop="useCardSource">
                  <Input v-model="formItem.useCardSource" placeholder="请咨询支付宝技术人员获取"></Input>
                </Form-item>
              </div>
            </div>
            <div class="init-config-sign fl clearfix">
              <h2 class="init-config-title">
                接口加签方式(请咨询小码技术同学获取)
              </h2>
              <div class="init-sign-left fl">
                <Form-item label="应用公钥Rsa1：" prop="appPublicKeyRsa1">
                  <Input v-model="formItem.appPublicKeyRsa1" type="textarea" placeholder="请输入"></Input>
                </Form-item>
                <Form-item label="应用私钥Rsa1：" prop="appPrivateKeyRsa1">
                  <Input v-model="formItem.appPrivateKeyRsa1" type="textarea" placeholder="请输入"></Input>
                </Form-item>
                <Form-item label="支付宝公钥1：" prop="alipayPublicKeyRsa1">
                  <Input v-model="formItem.alipayPublicKeyRsa1" type="textarea" placeholder="请输入"></Input>
                </Form-item>
              </div>
              <div class="init-sign-right fl">
                <Form-item label="应用公钥Rsa2：" prop="appPublicKeyRsa2">
                  <Input v-model="formItem.appPublicKeyRsa2" type="textarea" placeholder="请输入"></Input>
                </Form-item>
                <Form-item label="应用私钥Rsa2：" prop="appPrivateKeyRsa2">
                  <Input v-model="formItem.appPrivateKeyRsa2" type="textarea" placeholder="请输入"></Input>
                </Form-item>
                <Form-item label="支付宝公钥2：" prop="alipayPublicKeyRsa2">
                  <Input v-model="formItem.alipayPublicKeyRsa2" type="textarea" placeholder="请输入"></Input>
                </Form-item>
              </div>
            </div>
          </div>
        </div>
        <div class="init-content-submit">
          <Form-item>
            <Button type="primary" @click="verifyData('formItem')">校验信息</Button>
            <Button type="ghost" :disabled="disabled" @click="submit('formItem')">保存</Button>
          </Form-item>
        </div>
      </Form>
    </div>
  </div>
</template>
<script>
  import qs from 'qs'

  export default {
    data () {
      return {
        loginId: JSON.parse(sessionStorage.getItem('loginId')),
        intCheckbox: [],
        formItem: {
          userInfos: ['OPEN_FORM_FIELD_MOBILE', 'OPEN_FORM_FIELD_NAME', 'OPEN_FORM_FIELD_IDCARD'],
          name: '',
          appId: '',
          templateId: '',
          gateWay: 'https://openapi.alipay.com/gateway.do',
          authReturnUrl: '',
          cityCode: '',
          cardType: '',
          bizType: 'MEMBER_CARD',
          sence: 'TRANSIT',
          subSence: '',
          openCardVerifySource: '',
          openCardSuccessSource: '',
          useCardSource: '',
          appPublicKeyRsa1: '',
          appPublicKeyRsa2: '',
          appPrivateKeyRsa1: '',
          appPrivateKeyRsa2: '',
          alipayPublicKeyRsa1: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB',
          alipayPublicKeyRsa2: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB'
        },
        itemRules: {
          userInfos: [
            {required: true, type: 'array', min: 1, message: '至少选择一个信息', trigger: 'change'}
          ],
          name: [
            {required: true, message: '请输入应用名称', trigger: 'blur'}
          ],
          appId: [
            {required: true, message: '请输入appId', trigger: 'blur'},
            {len: 16, message: '请填写16位数字', trigger: 'blur'}
          ],
          templateId: [
            {required: true, message: '请输入TemplateId', trigger: 'blur'},
            {len: 25, message: '请填写25位数字', trigger: 'blur'}
          ],
          gateWay: [
            {required: true, message: '请输入支付宝网关', trigger: 'blur'},
            {type: 'url', message: '请输入正确的网址（https://或http://）', trigger: 'blur'}
          ],
          authReturnUrl: [
            {required: true, message: '请输入回调地址', trigger: 'blur'},
            {type: 'url', message: '请输入正确的网址（https://或http://）', trigger: 'blur'}
          ],
          cityCode: [
            {required: true, message: '请输入城市编码', trigger: 'blur'},
            {len: 6, message: '请填写6位数字', trigger: 'blur'}
          ],
          cardType: [
            {required: true, message: '请输入卡类型', trigger: 'blur'},
            {len: 8, message: '请填写8位字符，首位大写字母＋7位数字', trigger: 'blur'}
          ],
          bizType: [
            {required: true, message: '请输入bizType', trigger: 'blur'}
          ],
          sence: [
            {required: true, message: '请输入sence', trigger: 'blur'}
          ],
          subSence: [
            {required: true, message: '请输入subSence', trigger: 'blur'}
          ],
          openCardVerifySource: [
            {required: true, message: '领卡验证sourse', trigger: 'blur'}
          ],
          openCardSuccessSource: [
            {required: true, message: '开卡成功sourse', trigger: 'blur'}
          ],
          useCardSource: [
            {required: true, message: '用卡乘车sourse', trigger: 'blur'}
          ],
          appPublicKeyRsa1: [
            {required: false, message: '请同时输入或不输入应用公钥Rsa1/应用私钥Rsa1/支付宝公钥1', trigger: 'blur'}
          ],
          appPrivateKeyRsa1: [
            {required: false, message: '请同时输入或不输入应用公钥Rsa1/应用私钥Rsa1/支付宝公钥1', trigger: 'blur'}
          ],
          alipayPublicKeyRsa1: [
            {required: false, message: '请同时输入或不输入应用公钥Rsa1/应用私钥Rsa1/支付宝公钥1', trigger: 'blur'}
          ],
          appPublicKeyRsa2: [
            {required: false, message: '请同时输入或不输入应用公钥Rsa2/应用私钥Rsa1/支付宝公钥2', trigger: 'blur'}
          ],
          appPrivateKeyRsa2: [
            {required: false, message: '请同时输入或不输入应用公钥Rsa2/应用私钥Rsa1/支付宝公钥2', trigger: 'blur'}
          ],
          alipayPublicKeyRsa2: [
            {required: false, message: '请同时输入或不输入应用公钥Rsa2/应用私钥Rsa1/支付宝公钥2', trigger: 'blur'}
          ]
        },
        disabled: true
      }
    },
    created () {
      /* 第一步：获取多选框列表 */
      if (JSON.parse(sessionStorage.getItem('intCheckbox'))) {
        this.intCheckbox = JSON.parse(sessionStorage.getItem('intCheckbox'))
      } else {
        this.getCheckbox()
      }
      /* 第二步：获取用户历史配置信息 */
      if (JSON.parse(sessionStorage.getItem('formItem'))) {
        this.formItem = JSON.parse(sessionStorage.getItem('formItem'))
      } else {
        this.getInitInfor()
      }
      /* 第三步：填写并校验信息 */
      /* 第四步：提交并保存信息 */
    },
    methods: {
      /* 获取多选框列表 */
      getCheckbox () {
        let url = this.api.init.getCheckbox
        let params = {}
        this.$axios.get(url, {params: params}).then((res) => {
          if (res.data.msg.code === '20000') {
            this.intCheckbox = res.data.data
            sessionStorage.setItem('intCheckbox', JSON.stringify(res.data.data))
          } else {
            this.$Message.error({content: res.data.msg.message, duration: 5})
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error({content: '网络异常', duration: 5})
        })
      },
      /* 获取用户的历史配置信息 */
      getInitInfor () {
        let url = this.api.init.getInitInfor
        let params = {
          userId: this.loginId
        }
        this.$axios.get(url, {params: params}).then((res) => {
          if (res.data.msg.code === '20000') {
            if (res.data.data) {
              let initData = res.data.data
              sessionStorage.setItem('dataId', JSON.stringify(initData.id))
              sessionStorage.setItem('initData', JSON.stringify(initData))
              sessionStorage.setItem('appId', JSON.stringify(initData.appId))
              this.formItem = {
                userInfos: initData.userInfos.split(','),
                name: initData.name,
                appId: initData.appId,
                templateId: initData.templateId,
                gateWay: initData.gateWay,
                authReturnUrl: initData.authReturnUrl,
                cityCode: initData.alipayClientSubInfo.cityCode,
                cardType: initData.alipayClientSubInfo.cardType,
                bizType: initData.alipayClientSubInfo.bizType,
                sence: initData.alipayClientSubInfo.sence,
                subSence: initData.alipayClientSubInfo.subSence,
                openCardVerifySource: initData.alipayClientSubInfo.openCardVerifySource,
                openCardSuccessSource: initData.alipayClientSubInfo.openCardSuccessSource,
                useCardSource: initData.alipayClientSubInfo.useCardSource,
                appPublicKeyRsa1: initData.appPublicKeyRsa1,
                appPublicKeyRsa2: initData.appPublicKeyRsa2,
                appPrivateKeyRsa1: initData.appPrivateKeyRsa1,
                appPrivateKeyRsa2: initData.appPrivateKeyRsa2,
                alipayPublicKeyRsa1: initData.alipayPublicKeyRsa1,
                alipayPublicKeyRsa2: initData.alipayPublicKeyRsa2
              }
              sessionStorage.setItem('formItem', JSON.stringify(this.formItem))
            } else {
              this.$Message.error({content: '请配置相关信息', duration: 5})
            }
          } else {
            this.$Message.error({content: res.data.msg.message, duration: 5})
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error({content: '网络异常', duration: 5})
        })
      },
      /* 保存或更改配置信息 */
      initChange (params) {
        let url = this.api.init.initChange
        this.$axios.post(url, qs.stringify(params)).then((res) => {
          if (res.data.msg.code === '20000') {
            var dataId = res.data.data
            if (dataId || dataId === 0) {
              sessionStorage.setItem('dataId', JSON.stringify(dataId))
              this.getInitInfor()
              this.$Message.success({content: res.data.msg.message, duration: 5})
            }
          } else {
            this.$Message.error({content: res.data.msg.message, duration: 5})
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error({content: '网络异常', duration: 5})
        })
      },
      verifyBefore () {
        let keyOne = this.formItem.appPublicKeyRsa1 || this.formItem.appPrivateKeyRsa1
        if (keyOne) {
          this.itemRules.appPublicKeyRsa1[0].required = true
          this.itemRules.appPrivateKeyRsa1[0].required = true
          this.itemRules.alipayPublicKeyRsa1[0].required = true
        } else {
          this.itemRules.appPublicKeyRsa1[0].required = false
          this.itemRules.appPrivateKeyRsa1[0].required = false
          this.itemRules.alipayPublicKeyRsa1[0].required = false
        }
        let keyTwo = this.formItem.appPublicKeyRsa2 || this.formItem.appPrivateKeyRsa2
        if (keyTwo) {
          this.itemRules.appPublicKeyRsa2[0].required = true
          this.itemRules.appPrivateKeyRsa2[0].required = true
          this.itemRules.alipayPublicKeyRsa2[0].required = true
        } else {
          this.itemRules.appPublicKeyRsa2[0].required = false
          this.itemRules.appPrivateKeyRsa2[0].required = false
          this.itemRules.alipayPublicKeyRsa2[0].required = false
        }
      },
      verifyEnd () {
        this.itemRules.appPublicKeyRsa1[0].required = false
        this.itemRules.appPrivateKeyRsa1[0].required = false
        this.itemRules.alipayPublicKeyRsa1[0].required = false
        this.itemRules.appPublicKeyRsa2[0].required = false
        this.itemRules.appPrivateKeyRsa2[0].required = false
        this.itemRules.alipayPublicKeyRsa2[0].required = false
      },
      verifyData (name) {
        this.verifyBefore()
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.disabled = false
            this.$Message.success('表单验证成功!')
          } else {
            this.$Message.error('表单验证失败!')
            this.verifyEnd()
          }
        })
      },
      submit (name) {
        this.verifyBefore()
        this.$refs[name].validate((valid) => {
          if (valid) {
            var params = {
              userId: this.loginId,
              userInfos: this.formItem.userInfos.join(','),
              name: this.formItem.name,
              appId: this.formItem.appId,
              templateId: this.formItem.templateId,
              gateway: this.formItem.gateWay,
              authReturnUrl: this.formItem.authReturnUrl,
              cityCode: this.formItem.cityCode,
              cardType: this.formItem.cardType,
              bizType: this.formItem.bizType,
              sence: this.formItem.sence,
              subSence: this.formItem.subSence,
              openCardVerifySource: this.formItem.openCardVerifySource,
              openCardSuccessSource: this.formItem.openCardSuccessSource,
              useCardSource: this.formItem.useCardSource,
              appPublicKeyRsa1: this.formItem.appPublicKeyRsa1,
              appPublicKeyRsa2: this.formItem.appPublicKeyRsa2,
              appPrivateKeyRsa1: this.formItem.appPrivateKeyRsa1,
              appPrivateKeyRsa2: this.formItem.appPrivateKeyRsa2,
              alipayPublicKeyRsa1: this.formItem.alipayPublicKeyRsa1,
              alipayPublicKeyRsa2: this.formItem.alipayPublicKeyRsa2
            }
            var dataId = JSON.parse(sessionStorage.getItem('dataId'))
            if (dataId) {
              params.alipayClientInfoId = dataId
            }
            this.initChange(params)
            this.$Message.success('提交中。。。')
            this.disabled = true
          } else {
            this.$Message.error('表单验证失败!')
            this.disabled = true
            this.verifyEnd()
          }
        })
      }
    }
  }
</script>
